package cn.ludi.controller;

import cn.ludi.entity.LoginUser;
import cn.ludi.entity.User;
import cn.ludi.entity.UserRole;
import cn.ludi.entity.UserSession;
import cn.ludi.mapper.UserSessionMapper;
import cn.ludi.result.Result;
import cn.ludi.service.LoginService;
import cn.ludi.utils.JwtUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserSessionMapper userSessionMapper;

    @PostMapping("/login")
    public Result<String> login(@RequestBody User user){
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword()));
        if(!Objects.isNull(authenticate)){
            throw new RuntimeException("账号或密码错误");
        }
        //根据userid生成jwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        Long userId = loginUser.getUser().getId();
        Map<String,Object> map = new HashMap();
        map.put("userId",userId);
        String jwt = JwtUtil.createJWT("ludi",72000000,map);

        //把完整用户信息存入mysql中的session表
        //先检查是否有该条数据，如果有则为更新，否则为插入
        UserSession exist = userSessionMapper.getByUserId(userId);
        if(exist != null){
            exist.setUserInfo(JSON.toJSONString(loginUser));
            userSessionMapper.updateById(exist);
        }else{
            UserSession userSession = UserSession.builder()
                    .userId(userId)
                    .userInfo(JSON.toJSONString(loginUser))
                    .build();
            userSessionMapper.insert(userSession);
        }

        //携带令牌
        return Result.success(jwt);
    }

    public String logout(){
        return "登出成功";
    }

    public String update(){
        return "修改成功";
    }

    public String insert(){
        return "新增成功";
    }

    public String select(){
        return "查询功能";
    }
}
